package com.mall.interceptor;

import cn.hutool.core.convert.Convert;
import com.mall.utils.ThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一token处理的拦截器
 */
public class AuthorInterceptor implements HandlerInterceptor {
    /**
     * 接口方法执行之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取网关重置请求的请求头中的userId
        String id = request.getHeader("userId");
        //向本地线程存储当前用户id
        ThreadLocalUtil.setId(Convert.toLong(id));
        return true;
    }

    /**
     * 完成之后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       //清理当前线程变量副本
        ThreadLocalUtil.remove();
    }
}
